package pers.mor.tomcat.config;

import cn.hutool.log.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import pers.mor.tomcat.http.Constant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebXML {

    private static Map<String, String> mimeMapping = new HashMap<>();

    private static Element getRootElement() {
        Document doc = null;
        try {
            doc = new SAXReader().read(Constant.webXmlFile);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc.getRootElement();
    }

    public static List<Element> getTagList(String tag, String tagChild) {
        Element webApp = getRootElement();
        Element element = webApp.element(tag);
        List<Element> list = element.elements(tagChild);
        return list;
    }

    public static String getMimeType(String name) {
        String mimeType = mimeMapping.get(name);
        if (mimeType == null || mimeType.equals("")) {
            return "text/html";
        }
        return mimeType;
    }

    public static void initMimeTypeMap() {
        List<Element> tagList = getTagList("mime-type-list", "mime-mapping");
        for (Element e : tagList) {
            String key = e.elementText("extension");
            String value = e.elementText("mime-type");
            mimeMapping.put(key, value);
        }
    }

    public static String[] welcomeFilenames() {
        List<Element> tagList = getTagList("welcome-file-list", "welcome-file");
        String[] files = new String[tagList.size()];
        for (int i = 0; i < files.length; i++) {
            Element element = tagList.get(i);
            files[i] = element.getText();
        }
        return files;
    }

    public static int sessionTimeout() {
        List<Element> tagList = getTagList("session-config", "session-timeout");
        String text = tagList.get(0).getText();
        try {
            return Integer.valueOf(text);
        } catch (NumberFormatException e) {
            LogFactory.get().warn("启用 session 默认的时效配置 {} 分钟", 30);
            LogFactory.get().error("发现 session 时效配置 {} 错误 /conf/web.xml 中 <session-timeout> 只接受数字类型", text);
        }
        return 0;
    }

}
